package com.ljfiction.book.activitys;

import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.ljfiction.book.Baner.MessageBean;
import com.ljfiction.book.MyView.ContainsEmojiEditText;
import com.ljfiction.book.R;
import com.ljfiction.book.adapter.MessageAdapter;
import com.ljfiction.book.http.HttpManager;
import com.ljfiction.book.http.SoftHideKeyBoardUtil;
import com.ljfiction.book.http.UserManageBean;
import com.ljfiction.book.tools.KeyBoardHelper;
import com.ljfiction.book.tools.SettingManager;
import com.ljfiction.book.tools.StringTool;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

public class ToEmailActivity extends BaseActivity {

    @BindView(R.id.back_toemail)
    ImageView backToemail;
    @BindView(R.id.tousername)
    TextView tousername;
    @BindView(R.id.recycle_toemail)
    RecyclerView recycleToemail;
    @BindView(R.id.recomennt)
    ContainsEmojiEditText recomennt;
    @BindView(R.id.fasong_toemail)
    TextView fasongToemail;
    @BindView(R.id.refresh_message)
    SmartRefreshLayout refreshMessage;


    @BindView(R.id.toemail_backgroud)
    LinearLayout toemailBackgroud;
    @BindView(R.id.top_toemail)
    RelativeLayout topToemail;
    @BindView(R.id.bottom)
    LinearLayout bottom;


    private String touserid;
    private String touserName;
    private MessageAdapter mAdapter;
    private int page = 1;
    private MessageBean messageBean;
    private List<MessageBean.DataBean.ListBean> datas = new ArrayList<>();
    private List<MessageBean.DataBean.ListBean> datasfirst = new ArrayList<>();
    private String userImage;
    private InputMethodManager imm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_to_email);
        ButterKnife.bind(this);
        //getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        touserName = getIntent().getStringExtra("userName");
        touserid = getIntent().getStringExtra("userId");
        userImage = getIntent().getStringExtra("userImageUrl");
        tousername.setText(touserName);
        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        SoftHideKeyBoardUtil.assistActivity(this);

        intView();
        intData();
    }



    private void intData() {
        OkHttpUtils.get(HttpManager.IP + "/person-messageRecord/" + touserid + "/" + page)

                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        refreshMessage.finishRefresh();
                        Gson gson = new Gson();
                        try {
                            messageBean = gson.fromJson(s, MessageBean.class);
                            if (messageBean.getReturnCode() == 200) {
                                datasfirst.addAll(messageBean.getData().getList());
                                datas.clear();
                                datas.addAll(datasfirst);
                                Collections.reverse(datas);
                                for (MessageBean.DataBean.ListBean i :
                                        datas) {
                                    if (i.getUserId() == UserManageBean.userBean.getUserId()) {
                                        i.setUserImage(UserManageBean.userBean.getUserHeadPortraitURL());
                                    } else {
                                        i.setUserImage(userImage);
                                    }
                                }
                                mAdapter.notifyDataSetChanged();
                                recycleToemail.scrollToPosition(datas.size() - 1);
                            } else {
                                if (messageBean.getReturnCode() == 400){
                                    Intent intent=new Intent(ToEmailActivity.this,LoginActivity.class);
                                    startActivity(intent);
                                }
                                showToast(messageBean.getMsg());
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void intDataMore() {
        OkHttpUtils.get(HttpManager.IP + "/person-messageRecord/" + touserid + "/" + page)

                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        refreshMessage.finishRefresh();
                        Gson gson = new Gson();
                        try {
                            messageBean = gson.fromJson(s, MessageBean.class);
                            if (messageBean.getReturnCode() == 200) {
                                datasfirst.addAll(messageBean.getData().getList());
                                datas.clear();
                                datas.addAll(datasfirst);
                                Collections.reverse(datas);
                                for (MessageBean.DataBean.ListBean i :
                                        datas) {
                                    if (i.getUserId() == UserManageBean.userBean.getUserId()) {
                                        i.setUserImage(UserManageBean.userBean.getUserHeadPortraitURL());
                                    } else {
                                        i.setUserImage(userImage);
                                    }
                                }
                                mAdapter.notifyDataSetChanged();
                            } else {
                                if (messageBean.getReturnCode() == 400){
                                    Intent intent=new Intent(ToEmailActivity.this,LoginActivity.class);
                                    startActivity(intent);
                                }
                                showToast(messageBean.getMsg());
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void intView() {
        /*
        * 如果是官方就禁止发言
        * */
        if (touserid.equals("8184")){
            bottom.setVisibility(View.GONE);
        }
        mAdapter = new MessageAdapter(datas);
        recycleToemail.setAdapter(mAdapter);
        recycleToemail.setLayoutManager(new LinearLayoutManager(this));
        refreshMessage.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                if (messageBean.getData().isHasNextPage()){
                    page++;
                    intDataMore();
                }else {
                    refreshMessage.finishRefresh();
                }
            }
        });
        refreshMessage.setEnableLoadMore(false);
        recycleToemail.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                imm.hideSoftInputFromWindow(recomennt.getWindowToken(), 0);
                return false;
            }
        });
       /* toemailBackgroud.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {

            }
        });*/
       /* SoftKeyBoardListener.setListener(ToEmailActivity.this, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {
                bottom.scrollTo(0,120);
            }

            @Override
            public void keyBoardHide(int height) {
                bottom.scrollTo(0,0);
            }
        });*/
        recomennt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (String.valueOf(editable).length() >= 100) {
                    showToast("评论内容不能超过100个字");
                }
            }
        });
        bottom.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                if (oldBottom - bottom > 100) {
                    recycleToemail.scrollToPosition(datas.size() - 1);
                }
            }
        });
    }

    @OnClick({R.id.back_toemail, R.id.fasong_toemail})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_toemail:
                goBack();
                break;
            case R.id.fasong_toemail:
                if (!StringTool.isEmpty(recomennt.getText().toString())) {
                    OkHttpUtils.post(HttpManager.IP + "/person-sendmessage")

                            .params("userName", UserManageBean.userBean.getPseudonym())
                            .params("sendUserId", touserid)
                            .params("sendName", touserName)
                            .params("messageContent", StringTool.getJianjieText(recomennt.getText().toString()))
                            .execute(new StringCallback() {
                                @Override
                                public void onSuccess(String s, Call call, Response response) {
                                    try {
                                        JSONObject js = new JSONObject(s);
                                        if (js.getInt("returnCode") == 200) {
                                            recomennt.setText("");
                                            page = 1;
                                            datasfirst.clear();
                                            intData();
                                        } else {
                                            if (js.getInt("returnCode") == 400){
                                                Intent intent=new Intent(ToEmailActivity.this,LoginActivity.class);
                                                startActivity(intent);
                                            }
                                            showToast(js.getString("msg"));
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                }
                break;
        }
    }

}
